package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneItems;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import jdk.nashorn.internal.ir.EmptyNode;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        // 0 新建 1 已分配
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).
                        or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Override
    public void merge(MergeVo mergeVo) {
        // 1、采购单id为空,新建采购单
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            // 1.1 采购单状态为新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            // 1.2 采购单状态为新建
            purchaseId = purchaseEntity.getId();
        }
        // 2、合并采购单
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = Arrays.asList(mergeVo.getItems()).stream().map((id) -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            PurchaseEntity purchaseEntity = this.getById(finalPurchaseId);
//            // 如果不是正在采购
//            if (!(purchaseEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.BUYING.getCode())) {
//                // 设置成采购失败
//                purchaseEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
//            }
            // 状态设置为已分配
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailEntity.setId(id);
            // 设置采购单
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        // 根据id批量更新采购项
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    @Override
    public void received(List<Long> ids) {
        // 1、根据采购单id查询出采购状态
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(purchaseEntity -> {
            // 1.1 过滤掉 状态不是为新建或已分配的订单项 true 保存
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            // 1.2 状态设置成已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        // 根据id批量更新采购信息
        this.updateBatchById(purchaseEntityList);

        // 2、更新采购项
        purchaseEntityList.forEach((item) -> {
            // 2.1 根据采购单id查询出多个采购项
            List<PurchaseDetailEntity> purchaseDetailEntity = purchaseDetailService.listByDetailPurcharseId(item.getId());
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailEntity.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                // 2.2 状态设置成正在采购
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            // 根据id批量更新采购项信息
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
        });

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 1、更新采购项采购单状态
        // 1.1 采购项全部采购成功，采购单才能采购成功，一个采购项没有采购成功，那么采购单就不能采购成功
        boolean flag = true;
        // 更新集合
        List<PurchaseDetailEntity> updatePurchaseList = new ArrayList<>();
        List<PurchaseDoneItems> items = doneVo.getItems();
        for (PurchaseDoneItems item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            // 1.2 状态为采购失败
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                // 1.3 否则采购状态设置成已完成
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                // 1.4 添加库存
                wareSkuService.addStock(byId.getWareId(), byId.getSkuNum(), byId.getSkuId());
                // 1.5 设置状态已完成
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                purchaseDetailEntity.setId(item.getItemId());
                updatePurchaseList.add(purchaseDetailEntity);
            }
        }
        // 1.4 批量更新采购项信息
        purchaseDetailService.updateBatchById(updatePurchaseList);

        // 2、更新采购单状态
        // 2.1 根据flag 设置采购单状态为已完成 或 采购失败
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(doneVo.getId());
        this.updateById(purchaseEntity);
    }
}